package com.gsit.ocrbatch.services;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.gsit.ocrbatch.domain.Record;
import com.gsit.ocrbatch.domain.RecordState;

@Repository
public class RecordService {

	@PersistenceContext
	private EntityManager entityManager;
	
	
	@Transactional
	public void save(Record record) throws Exception {
		
		entityManager.merge(record);
		entityManager.flush();
		entityManager.clear();
		
	}
	
	public List<Record> findByAllWaitingRecords(){
		 TypedQuery<Record> typedQuery =entityManager.createNamedQuery("findByAllWaitingRecords",Record.class);
		 typedQuery.setParameter("recordState", RecordState.WAITING);
		 
		return  typedQuery.getResultList();
	}
	
	
	public Record findById(final Long id){
		return  entityManager.find(Record.class, id);
	}
	
	@Transactional
	public void setRecordState(final Long id,RecordState recordState){
		Record record= entityManager.find(Record.class, id);
		record.setRecordState(recordState);
		entityManager.merge(record);
		entityManager.flush();
		entityManager.clear();
	}
	
	@Transactional
	public void updateRecordState(Record record){
		entityManager.merge(record);
		entityManager.flush();
		entityManager.clear();
	}
	

}
